package com.sinba.common.system.dao;


import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;

import com.sinba.common.dao.BaseDAOImplHibernate;
import com.sinba.common.dto.PageDTO;
import com.sinba.common.system.dto.BuyCreditsQueryDTO;
import com.sinba.common.system.entity.BuyCredits;
import com.sinba.common.util.StringUtils;

public class BuyCreditsDAO extends BaseDAOImplHibernate<BuyCredits> implements IBuyCreditsDAO {

	public PageDTO findBuyCreditsPager(BuyCreditsQueryDTO qdto, String sord,
			String sidx) {
		// TODO Auto-generated method stub
		final DetachedCriteria dc = DetachedCriteria.forClass( BuyCredits.class );
		if(StringUtils.hasText(qdto.getLoginName())){
			dc.add(Restrictions.eq("loginName", qdto.getLoginName()));
		}
		if(StringUtils.hasText(qdto.getOperationsCenter())){
			dc.add(Restrictions.eq("operationsCenter", qdto.getOperationsCenter()));
		}
		
		
		if(StringUtils.hasText(qdto.getLinkCode())){
			dc.add(Restrictions.like("linkCode", qdto.getLinkCode(), MatchMode.START));
		}
		
		if(qdto.getStatus()!=null){
			dc.add(Restrictions.eq("status", qdto.getStatus()));
		}
		
		if(qdto.getStartRange()!=null && qdto.getEndRange()!=null){
			dc.add(Restrictions.between("buyMoney", qdto.getStartRange(), qdto.getEndRange()));
		}
		
		
		if ( ( sord != null ) && ! sord.equals( "" ) && ( sidx != null ) && ! sidx.equals( "" ) )
        {
            if ( sord.equals( "desc" ) )
            {
                dc.addOrder( Order.desc( sidx ) );
            } else{
                dc.addOrder( Order.asc( sidx ) );
            }
        }
		
		return super.findPageByCriteria(dc, qdto.getStart(), qdto.getLimit());
	}

	
	public boolean todayIsBuy(String loginName){
		final DetachedCriteria dc = DetachedCriteria.forClass( BuyCredits.class );
    	dc.add(Restrictions.eq("loginName", loginName));
    	Calendar timeStartCl = new GregorianCalendar(  );
        timeStartCl.setTime( new Date(  ) );
        timeStartCl.set( Calendar.HOUR_OF_DAY, 0 );
        timeStartCl.set( Calendar.MINUTE, 0 );
        timeStartCl.set( Calendar.SECOND, 0 );

        Calendar timeEndCl = new GregorianCalendar(  );
        timeEndCl.setTime( new Date(  ) );
        timeEndCl.set( Calendar.HOUR_OF_DAY, 23 );
        timeEndCl.set( Calendar.MINUTE, 59 );
        timeEndCl.set( Calendar.SECOND, 59 );

        dc.add( Restrictions.between( "createTime",
                                      timeStartCl.getTime(  ),
                                      timeEndCl.getTime(  ) ) );
    	Integer count = super.statCriteria( dc );
    	if(count!=null && count>0){
    		return true;
    	}else{
    		return false;
    	}
	};
	
}
